package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"loveserver/errno"
	"loveserver/middleware"
	"loveserver/model"
)

type ListUser struct {
	Total    uint64              	`json:"total"`
	DataList []model.UserModel 		`json:"dataList"`
}

// 用户登录
func Login(c *gin.Context){

	user := model.UserModel{
		Email:		c.PostForm("usernameemail"),
		Username:  c.PostForm("usernameemail"),
		Password: c.PostForm("password"),
	}
	//json绑定
	err :=c.BindJSON(&user)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	emailAndPwd := map[string]interface{}{"email": user.Email, "password": user.Password}
	usernameAndPwd := map[string]interface{}{"username": user.Username, "password": user.Password}
	users := user.FindByCondition(emailAndPwd)
	users2 := user.FindByCondition(usernameAndPwd)
	if len(users) != 0 {
		// 生成token
		jwt := middleware.NewJWT()
		tokenStr, _ := jwt.CreateToken(middleware.CustomClaims{
			Username: users[0].Username,
			Email:    users[0].Email,
		})
		// 将token放到json的data字段中返回
		SendResponse(c, errno.OK, map[string]interface{}{"token": tokenStr})
		return
	}

	if len(users2) != 0 {
		// 生成token
		jwt := middleware.NewJWT()
		tokenStr, _ := jwt.CreateToken(middleware.CustomClaims{
			Username: users2[0].Username,
			Email:    users2[0].Email,
		})
		// 将token放到json的data字段中返回
		SendResponse(c, errno.OK, map[string]interface{}{"token": tokenStr})
		return
	}

	// 根据用户名和密码 以及 邮箱和密码均找不到用户
	SendResponse(c, errno.ErrUserNotFound, map[string]interface{}{"message": "用户登录失败."})
}

// 用户注册
// todo 用户注册时候强制email和username都要输入 不能有一个不输入
func Register(c *gin.Context){

	user := model.UserModel{
		Email:		c.PostForm("email"),
		Username:  c.PostForm("username"),
		Password: c.PostForm("password"),
	}

	//绑定json
	err :=c.BindJSON(&user)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	// 检查用户名是否已经注册
	if len(user.FindByCondition(map[string]interface{}{"username": user.Username})) != 0 {
		SendResponse(c, errno.ErrUsernameExists, map[string]interface{}{"message": "用户名已注册."})
		return
	}

	// 检查邮箱是否已经注册
	if len(user.FindByCondition(map[string]interface{}{"email": user.Email})) != 0 {
		SendResponse(c, errno.ErrEmailExists,  map[string]interface{}{"message": "邮箱已注册."})
		return
	}

	// 创建一条记录，错误处理
	if err := user.Create(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	// 返回成功结果
	SendResponse(c, nil, map[string]interface{}{"message": "用户注册成功."})
}

// 获取用户信息
func GetUserInfo(c *gin.Context){

	token := c.Request.Header.Get("token")
	if token == "" {
		c.JSON(250, gin.H{
			"status": -1,
			"msg":    "请求未携带token，无权限访问",
		})
		c.Abort()
		return
	}

	j := middleware.NewJWT()
	// parseToken 解析token包含的信息
	claims, err := j.ParseToken(token)
	if err != nil {
		if err == middleware.TokenExpired {
			c.JSON(251, gin.H{
				"status": -1,
				"msg":    "授权已过期",
			})
			c.Abort()
			return
		}
		c.JSON(252, gin.H{
			"status": -1,
			"msg":    err.Error(),
		})
		c.Abort()
		return
	}

	// 返回用户的用户名和邮箱信息
	fmt.Println(claims.Username, claims.Email)
	SendResponse(c, errno.OK, map[string]interface{}{"username": claims.Username, "email": claims.Email})

}

// todo 实现修改密码
func UpdateUser(c *gin.Context){


}
